package com.clearance.mine_clearance.untils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clearance.mine_clearance.bot.MineClearanceBot;
import com.clearance.mine_clearance.bot.NumTest;
import com.clearance.mine_clearance.config.Constants;
import com.clearance.mine_clearance.entry.*;
import com.clearance.mine_clearance.mapper.*;
import com.clearance.mine_clearance.service.impl.KeyboardMarkupImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery;
import org.telegram.telegrambots.meta.api.methods.ParseMode;
import org.telegram.telegrambots.meta.api.methods.send.SendDice;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendPhoto;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageCaption;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.meta.api.objects.*;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

public class BotUntils {

    private static TgUserNapper tgUserNapper;
    private static BetInfoMapper betInfoMapper;
    private static RedUntils redUntils;
    private static CapitalMapper capitalMapper;
    private static InviterMapper inviterMapper;

    static {
        tgUserNapper = (TgUserNapper) BeanUtils.getBean("tgUserNapper");
        betInfoMapper = (BetInfoMapper) BeanUtils.getBean("betInfoMapper");
        redUntils = (RedUntils) BeanUtils.getBean("redUntils");
        capitalMapper = (CapitalMapper) BeanUtils.getBean("capitalMapper");
        inviterMapper = (InviterMapper) BeanUtils.getBean("inviterMapper");
    }

    /**
     * 充值
     */
    public static SendMessage topUp(Update update, String text) {
        SendMessage sendMessage = SendMessageUntils.initSendMessage(update.getMessage().getChatId().toString(), text);
        sendMessage.setReplyToMessageId(update.getMessage().getMessageId());
        sendMessage.setParseMode(ParseMode.HTML);
        List<InlineKeyboardButton> twoRow = new ArrayList<>();
        KeyboardMarkupImpl keyboardMarkup = new KeyboardMarkupImpl();
        InlineKeyboardButton topUpOrEithdraw = keyboardMarkup.getInlineKeyboardButton("财务", "https://t.me/JBGJ444");
        twoRow.add(topUpOrEithdraw);
        List<List<InlineKeyboardButton>> keyboard = new ArrayList<>();
        keyboard.add(twoRow);
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        //添加按钮行数;
        inlineKeyboardMarkup.setKeyboard(keyboard);
        sendMessage.setReplyMarkup(inlineKeyboardMarkup);
        return sendMessage;
    }

    public static SendMessage kefu(Update update, String text) {
        SendMessage sendMessage = SendMessageUntils.initSendMessage(update.getMessage().getChatId().toString(), text);
        sendMessage.setReplyToMessageId(update.getMessage().getMessageId());
        sendMessage.setParseMode(ParseMode.HTML);
        List<InlineKeyboardButton> twoRow = new ArrayList<>();
        KeyboardMarkupImpl keyboardMarkup = new KeyboardMarkupImpl();
        InlineKeyboardButton topUpOrEithdraw = keyboardMarkup.getInlineKeyboardButton("客服", "https://t.me/JBGJ234");
        twoRow.add(topUpOrEithdraw);
        List<List<InlineKeyboardButton>> keyboard = new ArrayList<>();
        keyboard.add(twoRow);
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        //添加按钮行数;
        inlineKeyboardMarkup.setKeyboard(keyboard);
        sendMessage.setReplyMarkup(inlineKeyboardMarkup);
        return sendMessage;
    }

    public static SendMessage groupUrl(Update update){
        /*Config config = RedisUntils.getConfig();
        String groupUrl = config.getGroupUrl();*/
        String message = "京博国际红包扫雷: "+"\n\n https://t.me/JBGJ66666";
        SendMessage sendMessage = SendMessageUntils.initSendMessage(update.getMessage().getChatId().toString(), message);
        sendMessage.setReplyToMessageId(update.getMessage().getMessageId());
        return sendMessage;
    }

    /**
     * 我的信息;
     */
    public static SendMessage UpdateaccountInformation(Update update) {
        TgUser tgUser = tgUserNapper.selectByTgId(update.getMessage().getChatId().toString());
        String message = "\uD83E\uDD35 呢称: <code>" + tgUser.getFirstName() + "</code>\n" +
                "\uD83D\uDCDB用户名: <a href=\"tg://user?id=" + tgUser.getTgId() + "\">" + tgUser.getUserName() + "</a>" + "\n" +
                "\uD83C\uDFF7\uFE0E id:  <code>" + tgUser.getTgId() + "</code>\n" +
                "\uD83D\uDCB8 账户余额<code>" + tgUser.getBalance() + "</code>";
        SendMessage sendMessage = SendMessageUntils.initSendMessage(update.getMessage().getChatId().toString(), message);
        sendMessage.setReplyToMessageId(update.getMessage().getMessageId());
        sendMessage.setParseMode(ParseMode.HTML);
        return sendMessage;
    }

    /**
     * 流水统计
     */
    public static SendMessage runningWaterStatistics(Update update) {
        TgUser tgUser = tgUserNapper.selectByTgId(update.getMessage().getFrom().getId().toString());
        Page<Capital> capitalPage = new Page<>(0, 50);
        LambdaQueryWrapper<Capital> capitalLambdaQueryWrapper = new LambdaQueryWrapper<>();
        capitalLambdaQueryWrapper.eq(Capital::getTgUserId, tgUser.getId());
        capitalLambdaQueryWrapper.orderByDesc(Capital::getTime);
        Page<Capital> selectPage = capitalMapper.selectPage(capitalPage, capitalLambdaQueryWrapper);
        List<Capital> capitalList = selectPage.getRecords();
        String message = "编号           变化金额            余额                 变动类型";
        for (int i = 1; i <= capitalList.size(); i++) {
            Capital capital = capitalList.get(i - 1);
            Integer type = capital.getType();
            String typeString = "";
            if (type.equals(0)) {
                typeString = "发红包";
            } else if (type.equals(1)) {
                typeString = "发红包返利";
            } else if (type.equals(2)) {
                typeString = "抢红包返利";
            } else if (type.equals(3)) {
                typeString = "中雷赔付";
            } else if (type.equals(4)) {
                typeString = "充值";
            } else if (type.equals(5)) {
                typeString = "提现";
            }else if(type.equals(6)){
                typeString = "群主佣金";
            }else if(type.equals(7)){
                typeString = "代理抽取";
            }
            message = message + "\n<code>" +
                    i + ".     " + capital.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP) + "     " + capital.getAfterAmount().setScale(2, BigDecimal.ROUND_HALF_UP) + "     " + typeString + "</code>";
        }
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(update.getMessage().getChatId());
        message = message + "\n            仅展示最新50条记录";
        sendMessage.setText(message);
        sendMessage.setParseMode(ParseMode.HTML);
        return sendMessage;
    }

    public static SendMessage startInit(Update update) {
        //判断是否有链接邀请信息;
        String text = update.getMessage().getText();
        text = text.replace(" ", "");
        text = text.substring(Constants.start.length());
        //查询当前的群组是否有这个链接;
        LambdaQueryWrapper<TgUser> tgUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tgUserLambdaQueryWrapper.eq(TgUser::getTgId, text);
        TgUser tgUser = tgUserNapper.selectOne(tgUserLambdaQueryWrapper);
        if (tgUser != null) {
            User user = update.getMessage().getFrom();
            //判断当前的用户是否有添加过;
            TgUser selectByTgId = tgUserNapper.selectByTgId(user.getId().toString());
            if (selectByTgId == null) {
                //我成为他的下级代理;
                TgUser tgUserInsert = new TgUser();
                tgUserInsert.setUserName(user.getUserName());
                tgUserInsert.setTgId(user.getId().toString());
                tgUserInsert.setIsBot(user.getIsBot() ? 0 : 1);
                String firstNam = "";
                if (StringUtils.isNotEmpty(user.getFirstName())) {
                    firstNam = firstNam + user.getFirstName();
                }
                if(StringUtils.isNotEmpty(user.getLastName())){
                    firstNam = firstNam +user.getLastName();
                }
                tgUserInsert.setFirstName(firstNam);
                tgUserInsert.setUserName(user.getUserName());
                tgUserInsert.setBalance(BigDecimal.ZERO);
                tgUserInsert.setType(0);
                tgUserInsert.setCreateTime(new Date());
                tgUserInsert.setGivePayType(0);
                tgUserInsert.setDarkLightning(1);
                tgUserInsert.setFrozenAmount(BigDecimal.ZERO);
                tgUserInsert.setChatInviteLinkUrl(InviteLinkUntils.getChatInviteIinkUrl(tgUserInsert));
                tgUserNapper.insert(tgUserInsert);
                RedisUntils.setValue(Constants.TGUSER + tgUserInsert.getTgId(), JSON.toJSONString(tgUserInsert));
                //设置邀请关系;
                Inviter inviter = new Inviter();
                inviter.setTime(new Date());
                inviter.setInviterTgId(tgUser.getId());
                inviter.setInviterTgUserId(tgUser.getTgId());
                inviter.setBeInviteTgId(tgUserInsert.getId());
                inviter.setBeInviterTgUserId(tgUserInsert.getTgId());
                inviterMapper.insert(inviter);
            }
        }
        Config config = RedisUntils.getConfig();
        SendMessage sendMessage = SendMessageUntils.initSendMessage(update.getMessage().getChatId().toString(), "✋， " + config.getUrl() + " 京博红包扫雷群欢迎体验!");
        sendMessage.setChatId(update.getMessage().getChatId());
        KeyboardRow keyboardRowOne = new KeyboardRow();
        List<String> listButtonNameRowOne = new ArrayList<>();
        listButtonNameRowOne.add(Constants.topUp);
        listButtonNameRowOne.add(Constants.withdraw);
        keyboardRowOne.addAll(listButtonNameRowOne);
        KeyboardRow keyboardRowTwo = new KeyboardRow();
        List<String> listButtonNameRowTwo = new ArrayList<>();
        listButtonNameRowTwo.add(Constants.accountInformation);
        listButtonNameRowTwo.add(Constants.customerService);
        listButtonNameRowTwo.add(Constants.groupUrl);
        keyboardRowTwo.addAll(listButtonNameRowTwo);
        List<KeyboardRow> rowList = new ArrayList<>();
        rowList.add(keyboardRowOne);
        rowList.add(keyboardRowTwo);
        KeyboardMarkupImpl keyboardMarkup = new KeyboardMarkupImpl();
        ReplyKeyboardMarkup replyKeyboardMarkup = keyboardMarkup.getReplyKeyboardMarkup(rowList);
        sendMessage.setReplyMarkup(replyKeyboardMarkup);
        return sendMessage;
    }


    /**
     * 账户金额;
     *
     * @return
     */
    public static AnswerCallbackQuery getMyAmount(CallbackQuery callbackQuery) {
        Long tgUserId = callbackQuery.getFrom().getId();
        TgUser tgUser = JSON.parseObject(RedisUntils.getValue(Constants.TGUSER + tgUserId), TgUser.class);
        AnswerCallbackQuery answerCallbackQuery = new AnswerCallbackQuery();
        answerCallbackQuery.setCallbackQueryId(callbackQuery.getId());
        answerCallbackQuery.setShowAlert(true);
        answerCallbackQuery.setText(tgUser.getFirstName() + "\n" + tgUser.getUserName() + "\n------------------\n" + "ID号:" + tgUser.getTgId() + "\n"
                + "余额:" + tgUser.getBalance().subtract(tgUser.getFrozenAmount()).stripTrailingZeros().toPlainString() + "\n交易中金额"
                + tgUser.getFrozenAmount().stripTrailingZeros().toPlainString());
        return answerCallbackQuery;
    }


    public static AnswerCallbackQuery promotionSelect(CallbackQuery callbackQuery) {
        LocalDateTime firstDayOfMonth = LocalDateTime.now().withDayOfMonth(1);
        LocalDateTime lastDayOfMonth = LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth());
        User user = callbackQuery.getFrom();
        String userString = RedisUntils.getValue(Constants.TGUSER + user.getId());
        TgUser tgUser = JSON.parseObject(userString, TgUser.class);
        //查询今日邀请的用户;
        LambdaQueryWrapper<Inviter> inviterLambdaQueryWrapper = new LambdaQueryWrapper<>();
        inviterLambdaQueryWrapper.eq(Inviter::getInviterTgId, tgUser.getId());
        inviterLambdaQueryWrapper.apply(true, "TO_DAYS(NOW())-TO_DAYS(time) = 0");
        //今日邀请的数量
        Integer toDayCount = inviterMapper.selectCount(inviterLambdaQueryWrapper);
        //查询本月邀请的数量;
        LambdaQueryWrapper<Inviter> inviterLambdaQueryWrapperMonth = new LambdaQueryWrapper<>();
        inviterLambdaQueryWrapperMonth.eq(Inviter::getInviterTgId, tgUser.getId());
        inviterLambdaQueryWrapperMonth.between(Inviter::getTime,firstDayOfMonth,lastDayOfMonth);
        Integer monthCount = inviterMapper.selectCount(inviterLambdaQueryWrapperMonth);
        //累计邀请
        LambdaQueryWrapper<Inviter> inviterLambdaQueryWrapperMonthAll = new LambdaQueryWrapper<>();
        inviterLambdaQueryWrapperMonthAll.eq(Inviter::getInviterTgId, tgUser.getId());
        Integer selectCount = inviterMapper.selectCount(inviterLambdaQueryWrapperMonthAll);
        String message = "今日邀请: " + toDayCount + "\n"
                + "本月邀请: " + monthCount + "\n" +
                "累计邀请" + selectCount + "\n------------\n" +
                "显示最后10条邀请\n 时间           用户昵称\n";
        //最新的10条邀请记录;
        LambdaQueryWrapper<Inviter> inviterLambdaQuery = new LambdaQueryWrapper<>();
        inviterLambdaQuery.eq(Inviter::getInviterTgId, tgUser.getId());
        inviterLambdaQuery.orderByDesc(Inviter::getTime);
        List<Inviter> inviterList = inviterMapper.selectList(inviterLambdaQuery);
        for (Inviter inviter : inviterList) {
            String time = DateUtil.fmort(inviter.getTime(), "yyyy-MM-dd");
            TgUser selectById = tgUserNapper.selectById(inviter.getBeInviteTgId());
            message = message+time+"           "+selectById.getFirstName()+"\n";
        }
       return SendMessageUntils.initAnswerCallbackQuery(callbackQuery,message);
    }

    /**
     * 今日盈亏;
     */
    public static AnswerCallbackQuery yearDayStatement(CallbackQuery callbackQuery) {
        Long id = callbackQuery.getFrom().getId();
        TgUser tgUser = tgUserNapper.selectByTgId(id.toString());
        LambdaQueryWrapper<Capital> capitalMapperLambdaQueryWrapper = new LambdaQueryWrapper<>();
        capitalMapperLambdaQueryWrapper.eq(Capital::getTgUserId, tgUser.getId());
        capitalMapperLambdaQueryWrapper.apply(true, "TO_DAYS(NOW())-TO_DAYS(time) = 1");
        List<Capital> capitalList = capitalMapper.selectList(capitalMapperLambdaQueryWrapper);
        //发包盈利系统抽成;
        //0发红包  1发红包返利 2抢红包   3中雷
        //收入-抢红包;
        BigDecimal robIncome = BigDecimal.ZERO;

        //支出发包
        BigDecimal zhiChuFaBao = BigDecimal.ZERO;

        //收入-发包-中雷盈利
        BigDecimal compensateProfit = BigDecimal.ZERO;

        //支出-抢包-中雷赔付
        BigDecimal compensateAmount = BigDecimal.ZERO;

        BigDecimal commissionIncomeValue = BigDecimal.ZERO;
        BigDecimal agencyIncomeValue = BigDecimal.ZERO;
        BigDecimal commission = BigDecimal.ZERO;
        //佣金
        for (Capital capital : capitalList) {
            if (capital.getType().equals(1)) {
                compensateProfit = compensateProfit.add(capital.getAmount());
            } else if (capital.getType().equals(0)) {
                zhiChuFaBao = zhiChuFaBao.add(capital.getAmount());
            } else if (capital.getType().equals(2)) {
                robIncome = robIncome.add(capital.getAmount());
            } else if (capital.getType().equals(3)) {
                compensateAmount = compensateAmount.add(capital.getAmount());
            } else if (capital.getType().equals(6)) {
                commissionIncomeValue = commissionIncomeValue.add(capital.getAmount());
            } else if (capital.getType().equals(7)) {
                agencyIncomeValue = agencyIncomeValue.add(capital.getAmount());
            }
        }
        //获取下级发包盈利抽成,查询我所有的下级;
        LambdaQueryWrapper<Inviter> inviterLambdaQueryWrapper = new LambdaQueryWrapper<>();
        inviterLambdaQueryWrapper.eq(Inviter::getInviterTgUserId, tgUser.getId());
        List<Inviter> inviterList = inviterMapper.selectList(inviterLambdaQueryWrapper);
        if (inviterList.size() > 0) {
            List<Integer> integerList = inviterList.stream().map(Inviter::getBeInviteTgId).collect(Collectors.toList());
            LambdaQueryWrapper<Capital> capitalLambdaQueryWrapper = new LambdaQueryWrapper<>();
            capitalLambdaQueryWrapper.in(Capital::getTgUserId, integerList);
            capitalLambdaQueryWrapper.eq(Capital::getType, 7);
            capitalLambdaQueryWrapper.apply(true, "TO_DAYS(NOW())-TO_DAYS(time) = 1");
            List<Capital> capitals = capitalMapper.selectList(capitalLambdaQueryWrapper);
            if (capitals.size() > 0) {
                for (Capital capital : capitals) {
                    commission = commission.add(capital.getAmount());
                }
            }
        }
        return SendMessageUntils.initAnswerCallbackQuery(callbackQuery,
                "今日报表:" + tgUser.getTgId() + "\n\n" +
                        "---------\n\n" +
                        "发包支出: " + zhiChuFaBao + "\n" +
                        "发包盈利: " + compensateProfit + "\n" +
                        "---------\n\n" +
                        "发包盈利系统抽成" + commissionIncomeValue + "\n" +
                        "发包盈利上级抽成" + agencyIncomeValue + "\n" +
                        "---------\n\n" +
                        "抢包收入: " + robIncome + "\n" +
                        "中雷赔付: " + compensateAmount + "\n" +
                        "---------\n\n" +
                        "下级发包盈利抽成: " + commission + "\n" +
                        "---------\n\n" +
                        "实际营收: " + compensateProfit.add(robIncome).add(commission).subtract(zhiChuFaBao)
                        .subtract(commissionIncomeValue).subtract(compensateAmount).subtract(agencyIncomeValue)
        );
        //(发包盈利+抢包收入+下级发包盈利抽成)-(发包支出+发包盈利系统抽成+中雷赔付+发包上级抽成)


    }

    /**
     * 今日盈亏;
     */
    public static AnswerCallbackQuery toDayStatement(CallbackQuery callbackQuery) {
        Long id = callbackQuery.getFrom().getId();
        TgUser tgUser = tgUserNapper.selectByTgId(id.toString());
        LambdaQueryWrapper<Capital> capitalMapperLambdaQueryWrapper = new LambdaQueryWrapper<>();
        capitalMapperLambdaQueryWrapper.eq(Capital::getTgUserId, tgUser.getId());
        capitalMapperLambdaQueryWrapper.apply(true, "TO_DAYS(NOW())-TO_DAYS(time) = 0");
        List<Capital> capitalList = capitalMapper.selectList(capitalMapperLambdaQueryWrapper);
        //发包盈利系统抽成;
        //0发红包  1发红包返利 2抢红包   3中雷
        //收入-抢红包;
        BigDecimal robIncome = BigDecimal.ZERO;
        //支出发包
        BigDecimal zhiChuFaBao = BigDecimal.ZERO;
        //收入-发包-中雷盈利
        BigDecimal compensateProfit = BigDecimal.ZERO;
        //支出-抢包-中雷赔付
        BigDecimal compensateAmount = BigDecimal.ZERO;
        BigDecimal commissionIncomeValue = BigDecimal.ZERO;
        BigDecimal agencyIncomeValue = BigDecimal.ZERO;
        BigDecimal commission = BigDecimal.ZERO;
        //佣金
        for (Capital capital : capitalList) {
            if (capital.getType().equals(1)) {
                compensateProfit = compensateProfit.add(capital.getAmount());
            } else if (capital.getType().equals(0)) {
                zhiChuFaBao = zhiChuFaBao.add(capital.getAmount());
            } else if (capital.getType().equals(2)) {
                robIncome = robIncome.add(capital.getAmount());
            } else if (capital.getType().equals(3)) {
                compensateAmount = compensateAmount.add(capital.getAmount());
            } else if (capital.getType().equals(6)) {
                commissionIncomeValue = commissionIncomeValue.add(capital.getAmount());
            } else if (capital.getType().equals(7)) {
                agencyIncomeValue = agencyIncomeValue.add(capital.getAmount());
            }
        }
        //获取下级发包盈利抽成,查询我所有的下级;
        LambdaQueryWrapper<Inviter> inviterLambdaQueryWrapper = new LambdaQueryWrapper<>();
        inviterLambdaQueryWrapper.eq(Inviter::getInviterTgId, tgUser.getId());
        List<Inviter> inviterList = inviterMapper.selectList(inviterLambdaQueryWrapper);
        if (inviterList.size() > 0) {
            List<Integer> integerList = inviterList.stream().map(Inviter::getBeInviteTgId).collect(Collectors.toList());
            LambdaQueryWrapper<Capital> capitalLambdaQueryWrapper = new LambdaQueryWrapper<>();
            capitalLambdaQueryWrapper.in(Capital::getTgUserId, integerList);
            capitalLambdaQueryWrapper.eq(Capital::getType, 7);
            capitalLambdaQueryWrapper.apply(true, "TO_DAYS(NOW())-TO_DAYS(time) = 0");
            List<Capital> capitals = capitalMapper.selectList(capitalLambdaQueryWrapper);
            if (capitals.size() > 0) {
                for (Capital capital : capitals) {
                    commission = commission.add(capital.getAmount());
                }
            }
        }
        return SendMessageUntils.initAnswerCallbackQuery(callbackQuery,
                "今日报表:" + tgUser.getTgId() + "\n\n" +
                        "---------\n\n" +
                        "发包支出: " + zhiChuFaBao + "\n" +
                        "发包盈利: " + compensateProfit + "\n" +
                        "---------\n\n" +
                        "发包盈利系统抽成" + commissionIncomeValue + "\n" +
                        "发包盈利上级抽成" + agencyIncomeValue + "\n" +
                        "---------\n\n" +
                        "抢包收入: " + robIncome + "\n" +
                        "中雷赔付: " + compensateAmount + "\n" +
                        "---------\n\n" +
                        "下级发包盈利抽成: " + commission + "\n" +
                        "---------\n\n" +
                        "实际营收: " + compensateProfit.add(robIncome).add(commission).subtract(zhiChuFaBao)
                        .subtract(commissionIncomeValue).subtract(compensateAmount).subtract(agencyIncomeValue)
        );
        //(发包盈利+抢包收入+下级发包盈利抽成)-(发包支出+发包盈利系统抽成+中雷赔付+发包上级抽成)
    }

    /**
     * 账户金额;
     *
     * @param update
     * @return
     */
    public static SendMessage getBlance(Update update) {
        Long tgUserId = update.getMessage().getFrom().getId();
        TgUser tgUser = JSON.parseObject(RedisUntils.getValue(Constants.TGUSER + tgUserId), TgUser.class);
        SendMessage sendMessage = SendMessageUntils.initSendMessage(update.getMessage().getChatId().toString(), "用户ID: " + tgUser.getTgId() + "\n" +
                "用户昵称: " + tgUser.getUserName() + "\n" +
                "当前余额: " + tgUser.getBalance().stripTrailingZeros().toPlainString()+"U");
        sendMessage.setReplyToMessageId(update.getMessage().getMessageId());
        return sendMessage;
    }

    /**
     * 发送红包;
     * 发送红包;
     */
    public static SendPhoto giveRedEnvelopes(Update update) {
        Config config = RedisUntils.getConfig();
        String text = update.getMessage().getText();
        TgUser tgUser = JSON.parseObject(RedisUntils.getValue(Constants.TGUSER + update.getMessage().getFrom().getId()), TgUser.class);
        String[] split = text.split("-");
        BigDecimal amount = new BigDecimal(split[0]);
        //判断是否超出最大最小金额;
        if (amount.doubleValue() < config.getMinRedPacket().doubleValue() || amount.doubleValue() > config.getMaxRedPacket().doubleValue()) {
            SendMessage sendMessage = SendMessageUntils.initSendMessage(config.getGroupChatId(), "❌发送失败,金额必须大于【" + config.getMinRedPacket() + "】\" \n" +
                    "                                \"小于【" + config.getMaxRedPacket() + "】");
            sendMessage.setReplyToMessageId(update.getMessage().getMessageId());
            new MineClearanceBot().sendMessage(sendMessage);
            return null;
        }
        //雷数;
        Integer ray = Integer.valueOf(split[1]);
        RedPacket redPacket = new RedPacket();
        redPacket.setTgUserId(tgUser.getId());
        redPacket.setAmount(amount);
        redPacket.setMulriple(config.getMulriple());
        redPacket.setRob(0);
        redPacket.setRedPacketSum(config.getRedPacketSum());
        redPacket.setTime(new Date());
        redPacket.setMines(ray);
        redPacket.setCommissionIncome(BigDecimal.ZERO);
        redPacket.setZhongleiProfit(BigDecimal.ZERO);
        redPacket.setAgencyIncome(BigDecimal.ZERO);
        redPacket.setActualArrival(BigDecimal.ZERO);
        //进行数据拆分;
        try {
            redUntils.giveRedEnvelopesTask(tgUser, redPacket, update.getMessage().getMessageId(), true);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 抢红包;
     */
    public static EditMessageCaption robRed(CallbackQuery callbackQuery) {
        //判断我是否已经抢过当前的红包了?
        EditMessageCaption editMessageCaption = new EditMessageCaption();
        Message message = callbackQuery.getMessage();
        editMessageCaption.setMessageId(message.getMessageId());
        editMessageCaption.setChatId(message.getChatId());
        //查询当前的红包呢信息;
        String text = callbackQuery.getData();
        String redPacketId = text.substring(Constants.redPacket.length());
        User user = callbackQuery.getFrom();
        //判断是不去抢自己的红包;

        LambdaQueryWrapper<BetInfo> betInfoLambdaQueryWrapperSel = new LambdaQueryWrapper<>();
        betInfoLambdaQueryWrapperSel.eq(BetInfo::getRedpacketId, redPacketId);
        betInfoLambdaQueryWrapperSel.eq(BetInfo::getTgUserId, user.getId());
        TgUser tgUser = JSON.parseObject(RedisUntils.getValue(Constants.TGUSER + user.getId()), TgUser.class);
        BetInfo selectOne = betInfoMapper.selectOne(betInfoLambdaQueryWrapperSel);
        if (selectOne != null) {
            AnswerCallbackQuery answerCallbackQuery = SendMessageUntils.initAnswerCallbackQuery(callbackQuery, "您已抢当前红包无需在抢!");
            new MineClearanceBot().sendMessage(answerCallbackQuery);
            return null;
        }
        //发包详情;
        redUntils.addIndex(Integer.valueOf(redPacketId), tgUser, callbackQuery);
        return null;
    }
}





































